// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Su Hao (suhao@baidu.com)
//
// Description: Report the Play Events.

#include <mbed.h>
#include "duer_play_command_manager.h"
#include "duer_play_command.h"
#include "heap_monitor.h"

using duer::PlayCommandManager;

PlayCommandManager PlayCommandManager::s_instance;

PlayCommandManager &PlayCommandManager::instance(void)
{
    return s_instance;
}

PlayCommandManager::PlayCommandManager()
    : _events(NULL)
{
}

PlayCommandManager::~PlayCommandManager()
{
    clear_command();

    if (_events) {
        baidu_util_list_destroy(_events);
        _events = NULL;
    }
}

int PlayCommandManager::add_command(baidu_json *action)
{
    if (_events == NULL) {
        _events = baidu_util_list_create();
    }

    if (_events) {
        PlayCommand *event = NEW(UTILITY) PlayCommand();
        event->set_action(action);

        baidu_util_list_append(_events, event);
    }

    return 0;
}

int PlayCommandManager::start()
{
    PlayCommand *event = reinterpret_cast<PlayCommand *>(baidu_util_list_get(_events, 0));
    if (event) {
        event->start();
    }

    return 0;
}

int PlayCommandManager::stop()
{
    PlayCommand *event = reinterpret_cast<PlayCommand *>(baidu_util_list_remove(_events, 0));
    if (event) {
        event->stop();
        delete event;
    }

    return 0;
}

int PlayCommandManager::end()
{
    PlayCommand *event = reinterpret_cast<PlayCommand *>(baidu_util_list_get(_events, 0));
    if (event) {
        event->end();
        if (!event->has_data()) {
            baidu_util_list_remove(_events, 0);
            delete event;
        }
    }

    return 0;
}

int PlayCommandManager::next()
{
    PlayCommand *event = reinterpret_cast<PlayCommand *>(baidu_util_list_get(_events, 0));
    if (event) {
        event->next();
    }

    return 0;
}

int PlayCommandManager::previous()
{
    PlayCommand *event = reinterpret_cast<PlayCommand *>(baidu_util_list_get(_events, 0));
    if (event) {
        event->previous();
    }

    return 0;
}

int PlayCommandManager::repeat()
{
    PlayCommand *event = reinterpret_cast<PlayCommand *>(baidu_util_list_get(_events, 0));
    if (event) {
        event->repeat();
    }

    return 0;
}

void PlayCommandManager::clear_command(void)
{
    PlayCommand *event = NULL;

    do {
        event = reinterpret_cast<PlayCommand *>(baidu_util_list_remove(_events, 0));
        if (event) {
            delete event;
        }
    } while (event != NULL);
}
